import axios from "axios";
import express from "express";
import { PrismaClient } from "@prisma/client";
import { CreateId, Check, Result, Time } from "@/utils";

const prisma = new PrismaClient();
const router = express.Router();

// 检查是否存在管理员账号
router.get("/checkAdmin", async (req, res) => {
   res.send(Result.OK({ hasUser: false }));
});

/** 发送短信验证码 */
router.post("/sendMessage", async (req, res) => {
   const { phone }: Common.sendMessage = req.body;
   if (!Check.Mobile(phone)) return res.send(Result.Error("手机号码格式错误"));

   /**
    * 检测当前号码是否重复发送
    * 发送间隔：1分钟
    */
   const his = await prisma.sms.findFirst({
      where: {
         phone,
         send_time: { gte: new Date(Time.Now().getTime() - 60000) }
      }
   });

   if (his != null) return res.send(Result.Error("重复发送"));

   // 创建随机数
   const code = (Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000).toString();

   // 发送短信接口数据
   const params = {
      appid: "62475", // Appid
      signature: "ee23c55b6add2e98a510baaf6d4dafad", // App key
      project: "ng0LY", // 短信模板
      to: phone, // 手机号码
      vars: `{"code": ${code}, "time": "10"}`
   };

   // 发送短信
   const result = await axios.post("https://api-v4.mysubmail.com/sms/xsend.json", params);
   const { status, send_id } = result.data;

   // 插入数据
   const add = await prisma.sms.create({
      data: {
         id: await CreateId.One("sms"),
         send_time: Time.Now(),
         send_id,
         status,
         phone,
         code
      }
   });

   res.send(Result.OK({ smgId: add.id }));
});

export const common = router;
